﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Bookmark.Net.Models;

namespace Bookmark.Net.Controllers
{
    public class ItemControllerViewData
    {
        public PagedList<Item> Items{ get; set;}
        public Item Item { get; set; }
        public List<Tag> Tags { get; set; }
        public List<Tag> RelatedTags { get; set; }
        public string userName { get; set; }
        public string tagName { get; set; }
        public string SearchText { get; set; }
        public string ErrorMessage { get; set; }
        public string Url { get; set; }
        public string Title { get; set; }
        public string TagString { get; set; }

    }
    public class ItemController : Controller
    {
        public const int ITEMTYPE_BOOKMARK = 1;

        private Bookmark_NetDataContext db = new Bookmark_NetDataContext();
        private ItemControllerViewData viewData = new ItemControllerViewData();

        public void Search(int? page)
        {
            // TODO: 
        }
        public void List(int? page, string userName, string tagName)
        {
            //page = page ?? 0;
            //userName = userName ?? "all";
            //tagName = tagName ?? "";
            viewData.tagName = tagName;
            if (userName == null || userName == string.Empty || userName.ToLower() == "all")
            {
                viewData.userName = "all";
                viewData.Tags = db.Tags.ToList();
                if (tagName == null || tagName == string.Empty)
                {

                    viewData.Items = db.GetItems(page);
                }
                else
                {
                    viewData.RelatedTags = db.GetRelatedTags(tagName);
                    viewData.Items = db.GetItemsByTag(page, tagName);
                }
            }
            else
            {
                viewData.userName = userName;
                viewData.Tags = db.Tags.Where(t => t.User.UserName == userName).ToList();
                if (tagName == null || tagName == string.Empty)
                {

                    viewData.Items = db.GetItemsByUser(page, userName);
                }
                else
                {
                    viewData.RelatedTags = db.GetRelatedTagsOfUser(tagName, userName);
                    viewData.Items = db.GetItemsByUserTag(page, userName, tagName);
                }

            }

            RenderView("List", viewData);
        }
        public void New(string url, string title)
        {
            if(url==null) 
                url = string.Empty;
            else
                url = url.Trim();
            if(title==null)
                title = string.Empty;
            else
                title = title.Trim();

            int userId = GetUserID();
            try
            {
                viewData.Item = db.Items.Single(i => i.UserId == userId && i.ShortCut == url);
                if (viewData.Item != null)
                    Edit(viewData.Item.ItemId);
            }
            catch (Exception ex)
            {
                viewData.Item = new Item();
                viewData.Item.ShortCut = url;
                viewData.Item.Title = title;
                SetTags(userId);
                RenderView("New", viewData);
            }
                


        }
        public void Edit(int id)
        {
            //if (db.Users.Single(u => u.NetworkLogin == this.HttpContext.User.Identity.Name) == null)
            //{
            //    viewData.ErrorMessage = "Error: You have not yet registered.";
            //    RenderView("List", viewData);
            //    //RedirectToAction("New", "User");
            //    return;
            //}
            if (viewData.Item == null)
            {
                viewData.Item = db.Items.Single(i => i.ItemId == id);
            }
            int userId = GetUserID();
            SetTags(userId);
            RenderView("Edit", viewData);
        }
        private int GetUserID()
        {
            // if user doesnt exist just create them - for now we'll just use network name (less domain)
            string networkLogin = this.HttpContext.User.Identity.Name;
            User usr = db.Users.Single(u => u.NetworkLogin == networkLogin);
            if (usr == null)
            {
                usr = new User();
                usr.NetworkLogin = networkLogin;
                usr.UserName = networkLogin.Substring(networkLogin.LastIndexOf('\\') + 1);
                db.Users.InsertOnSubmit(usr);
                db.SubmitChanges();
                usr = db.Users.Single(u => u.NetworkLogin == networkLogin);
            }
            return usr.UserId;
        }
        private void SetTags(int userId)
        {
            viewData.Tags = db.Tags.Where(t => t.UserId==userId).ToList();
        }
        public void Create()
        {
            try
            {
                int userId = this.GetUserID();
                string shortCut = Request.Form["Item.ShortCut"].Trim();
                Item itemExists = null;
                try
                {
                    itemExists = db.Items.Single(i => i.UserId == userId && i.ShortCut == shortCut);
                }
                catch (Exception exItem)
                {
                }
                if (itemExists != null)
                {
                    viewData.Item = itemExists;
                    Edit(itemExists.ItemId);

                }
                else
                {
                    viewData.Item = new Item();
                    viewData.Item.CreateDate = DateTime.Today;
                    viewData.Item.Description = Request.Form["Item.Description"].Trim();
                    //viewData.Item.Private = false; // todo
                    viewData.Item.ShortCut = shortCut;
                    viewData.Item.Title = Request.Form["Item.Title"].Trim();
                    viewData.Item.UpdateDate = DateTime.Today;
                    viewData.Item.UserId = userId;
                    viewData.Item.ItemTypeId = ITEMTYPE_BOOKMARK;
                    db.Items.InsertOnSubmit(viewData.Item);
                    db.SubmitChanges();
                    viewData.Item = db.Items.Single(i => i.UserId == userId && i.ShortCut == Request.Form["Item.ShortCut"]);

                    string tagString = Request.Form["TagString"].Trim();

                    if (tagString != null && tagString.Trim() != string.Empty)
                    {
                        string[] tags = tagString.Trim().Split(' ');
                        viewData.ErrorMessage = "num tags: " + tags.Length.ToString();
                        for (int i = 0; i < tags.Length; i++)
                        {
                            Tag tag = null;
                            try
                            {
                                tag = db.Tags.Single(t => t.UserId == userId && t.TagName == tags[i]);
                            }
                            catch (Exception exTag)
                            {
                            }
                            if (tag == null)
                            {
                                tag = new Tag();
                                tag.TagName = tags[i];
                                tag.UserId = userId;
                                db.Tags.InsertOnSubmit(tag);
                                db.SubmitChanges();
                                tag = db.Tags.Single(t => t.UserId == userId && t.TagName == tags[i]);
                            }
                            ItemTag itemTag = new ItemTag();
                            itemTag.ItemId = viewData.Item.ItemId;
                            itemTag.TagId = tag.TagId;
                            db.ItemTags.InsertOnSubmit(itemTag);

                        }
                    }


                    db.SubmitChanges();
                    RedirectToAction("List");
                }
            }
            catch (Exception err)
            {
                viewData.ErrorMessage = err.ToString() + err.Message + " " + err.StackTrace;
                viewData.Item = new Item();
                RenderView("New", viewData);
            }

        }

    }
}
